#!/usr/bin/python
# coding =utf-8
import logging
import getpass
import telnetlib
import time
import sys
import os


class Tel:
    def __init__(self, host, user, password, logpath='debug_tel.log'):
        self.host = host
        self.user = user
        self.user = getpass.getuser() if user is None else user
        self.password = getpass.getpass() if password is None else password
        self.session = None
        self.pmpt = '>'
        if logpath is not None and logpath != '':
            if not os.path.exists(logpath):
                with open(logpath, "w") as f:
                    f.close()
            logging.basicConfig(level=logging.DEBUG,
                                format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                                datefmt='%a, %d %b %Y %H:%M:%S',
                                filename=logpath,
                                filemode='w')
        if host is not None:
            self.login()

    def popbuff(self):
        time.sleep(.3)
        buff = self.session.read_eager()
        tmpbuff = "tmp"
        while tmpbuff != '':
            tmpbuff = self.session.read_eager()
            buff = buff + tmpbuff
        logging.debug("buffer :{buff}".format(buff=buff))
        return buff

    def getdefaultpmpt(self):
        self.session.write(b"hostname\n")
        result = self.popbuff()
        logging.debug('get hostname result= %s' % result)
        return result.split('\n')[-1]

    def login(self):
        conn = telnetlib.Telnet(host=self.host)
        conn.read_until(b"login: ")
        conn.write(self.user.encode('ascii') + b"\n")
        conn.read_until(b"Password: ")
        conn.write(self.password.encode('ascii') + b"\n")
        self.session = conn
        self.pmpt = self.getdefaultpmpt()
        print ("login successfully!")

    def exec_cmd(self, cmd):
        print('pmpt=' + self.pmpt)
        self.popbuff()
        logging.debug('start exec cmd %s' % cmd)
        self.session.write(b'%s\n' % cmd)
        result = self.session.read_until(self.pmpt)
        logging.debug('execmd=%s,result=%s' % (cmd, result))
        return result

    def logout(self):
        if self.session is not None:
            self.session.close()


if __name__ == '__main__':
    tel = Tel('localhost', user='shao', password='123456')
    print(tel.exec_cmd("whoami"))
    print(tel.exec_cmd('pwd'))
    print(tel.exec_cmd('uname -a'))
    tel.logout()
